import React from 'react';
import { Bar } from 'react-chartjs-2';
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend
} from 'chart.js';

ChartJS.register(
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend
);

export const MostVisitedChart = ({ timeSpentByDomain, limit = 10 }) => {
  const sortedDomains = Object.entries(timeSpentByDomain)
    .sort((a, b) => b[1].visits - a[1].visits)
    .slice(0, limit);

  const data = {
    labels: sortedDomains.map(([domain]) => domain.length > 25 ? domain.substring(0, 25) + '...' : domain),
    datasets: [
      {
        label: 'Visits',
        data: sortedDomains.map(([, data]) => data.visits),
        backgroundColor: 'rgba(72, 187, 120, 0.8)',
        borderColor: 'rgba(72, 187, 120, 1)',
        borderWidth: 1
      }
    ]
  };

  const options = {
    indexAxis: 'y',
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
      legend: {
        display: false
      },
      tooltip: {
        callbacks: {
          label: function(context) {
            return `${context.parsed.x} visits`;
          }
        }
      }
    },
    scales: {
      x: {
        beginAtZero: true,
        ticks: {
          color: 'rgba(255, 255, 255, 0.7)',
          precision: 0
        },
        title: {
          display: true,
          text: 'Number of Visits',
          color: 'rgba(255, 255, 255, 0.7)'
        }
      },
      y: {
        ticks: {
          color: 'rgba(255, 255, 255, 0.7)'
        }
      }
    }
  };

  return (
    <div style={{ height: '400px', width: '100%' }}>
      <Bar data={data} options={options} />
    </div>
  );
};

